<template>
  <div class="main-box-admin">
    <el-breadcrumb separator="/" style="font-size: 18px;">
      <el-breadcrumb-item :to="{ path: '/TanHome/ManageCarbon' }">碳排放输入管理首页</el-breadcrumb-item>
      <el-breadcrumb-item>碳排放输入列表</el-breadcrumb-item>
    </el-breadcrumb>
    <br>
    <div>
      <div class="flex-box-header">
        <div class="energyleft">
          <el-form>
            <el-tag style="font-size: 13px;">输入物品名称：</el-tag>
            <el-form-item style="display: inline-block">
              <el-input v-model="objectName" placeholder="请输入物品名称" size="small"></el-input>
            </el-form-item>
            <el-button class="form-item-inline" size="small" @click="searchCarbon" plain
              icon="el-icon-search">查询</el-button>
            <el-button class="form-item-inline" type="success" size="small" @click="getAllEmission" plain
              icon="el-icon-search">显示全部物品</el-button>
          </el-form>
        </div>
        <div class="energyright">
          <el-form>
            <el-button class="form-item-inline" type="primary" size="small" @click="insertEmission">新增碳排放物品</el-button>
            <el-button class="form-item-inline" type="primary" size="small" @click="getexcelEmission">导入碳排放物品</el-button>
          </el-form>
        </div>
      </div>
      <div class="table_container" style="width: 100%; overflow: auto; ">
        <el-table :data="tableData" style="width: 100%;font-size: 15px; " size="small">
          <el-table-column prop="objectName" label="物品名称"></el-table-column>
          <el-table-column prop="objectCategory" label="物品类型" ></el-table-column>
          <el-table-column prop="objectConsumption" label="物品消耗量" ></el-table-column>
          <el-table-column prop="emissionType" label="物品排放类型" ></el-table-column>
          <el-table-column prop="emissionPurpose" label="排放用途" ></el-table-column>
          <el-table-column prop="emissionAmount" label="碳排放量" ></el-table-column>
          <el-table-column prop="emissionBuilding" label="排放地点（楼宇）"></el-table-column>
          <el-table-column prop="emissionYear" label="输入时间（年）" ></el-table-column>
          <el-table-column prop="emissionMonth" label="输入时间（月）" ></el-table-column>
          <el-table-column label="操作" width="200px" style="white-space:nowrap;">
            <template slot-scope="scope">
              <div class="updBtn" style="display: inline-block;"><el-button @click="updateEmission(scope.row)" type="warning" plain size="small"
                  icon="el-icon-edit">修改</el-button></div>
              <div class="delBtn" style="display: inline-block;"><el-button @click="deleteEmission(scope.row)" type="danger" plain size="small"
                  icon="el-icon-delete">删除</el-button></div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 换页菜单 -->
        <div style="text-align:center; margin:20px;padding-right: 50px;">
          <el-pagination background @current-change="handleCurrentChange" :page-size="limit" :current-page="1"
            layout="total, prev, pager, next" :total="total">
          </el-pagination>
        </div>
      </div>
      <div class="upload-image">
        <el-dialog title="碳排放物品输入添加" :visible.sync="emissionInsertForm" width="40%">
          <el-form :model="newEmissionData" ref="ruleForm" label-width="180px">
            <el-form-item label="物品名称" prop="objectName">
              <el-input v-model="newEmissionData.objectName" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物品类型" prop="objectCategory">
              <el-input v-model="newEmissionData.objectCategory" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物品消耗量" prop="objectConsumption">
              <el-input v-model="newEmissionData.objectConsumption" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物品排放类型">
              <el-select v-model="newEmissionData.emissionType" placeholder="请选择物品排放类型">
                <el-option label="直接排放" value="0"></el-option>
                <el-option label="间接排放" value="1"></el-option>
                <el-option label="其他排放" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排放用途" prop="emissionPurpose">
              <el-input v-model="newEmissionData.emissionPurpose" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="碳排放量" prop="emissionAmount">
              <el-input v-model="newEmissionData.emissionAmount" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="排放地点（楼宇）" prop="emissionBuilding">
              <el-input v-model="newEmissionData.emissionBuilding" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="输入时间（年）" prop="emissionYear">
              <el-date-picker v-model="newEmissionData.emissionYear" type="year" value-format='yyyy' placeholder="选择年">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="输入时间（月）" prop="emissionMonth">
              <el-input v-model="newEmissionData.emissionMonth" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="insertEmissionData">确认添加</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div class="upload-image">
        <el-dialog title="碳排放物品输入修改" :visible.sync="emissionUpdateForm" width="40%">
          <el-form :model="updateEmissionData" ref="ruleForm" label-width="180px">
            <el-form-item label="物品名称" prop="objectName">
              <el-input v-model="updateEmissionData.objectName" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物品类型" prop="objectCategory">
              <el-input v-model="updateEmissionData.objectCategory" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物品消耗量" prop="objectConsumption">
              <el-input v-model="updateEmissionData.objectConsumption" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物品排放类型">
              <el-select v-model="updateEmissionData.emissionType" placeholder="请选择课程类型">
                <el-option label="直接排放" value="0"></el-option>
                <el-option label="间接排放" value="1"></el-option>
                <el-option label="其他排放" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排放用途" prop="emissionPurpose">
              <el-input v-model="updateEmissionData.emissionPurpose" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="碳排放量" prop="emissionAmount">
              <el-input v-model="updateEmissionData.emissionAmount" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="排放地点（楼宇）" prop="emissionBuilding">
              <el-input v-model="updateEmissionData.emissionBuilding" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="输入时间（年）" prop="emissionYear">
              <el-date-picker v-model="updateEmissionData.emissionYear" type="year" value-format='yyyy' placeholder="选择年">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="输入时间（月）" prop="emissionMonth">
              <el-input v-model="updateEmissionData.emissionMonth" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="modifyEmissionData">立即修改</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div class="upload-image" style="width: 300px">
        <el-dialog class="self_define" title="导入碳排放物品列表" :close-on-click-modal='false' :visible.sync="emissionAddForm"
          width="40%">
          <el-form :model="fileRes" ref="ruleForm" label-width="100px">
            <el-form-item label="" ref="uploadElement" prop="photoUrl" style="margin: 0 auto">
              <el-upload class="upload-demo" ref="upload" drag :action="UploadEnergyUrl()" multiple :auto-upload="false"
                :on-success="handleSuccessEnergy" :on-error="uploadEnergyError" :before-upload="getFileType" :limit="5"
                :file-list="fileList" name="file">
                <i class="el-icon-upload"></i>
                <div slot="tip" class="el-upload__tip">只能上传一个.xlsx 文件</div>
                <div slot="tip" class="el-upload__tip" style="width: 100%; word-break:break-all;">
                  传入的xlsx文件第一行必须为为表头(物品名称，物品分类，物品消耗量，排放类型，排放用途，排放时间(年)，排放时间（月），碳排放量，排放地点)</div>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addNewEmission">确定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import { publicNetworkIpAndPort } from "../../api/globalVar";
import { getAllEmission, searchCarbonByName } from "../../api/user";
export default {
  data() {
    return {
      current: 1,
      size: 10,
      cur: 1,
      fileRes: {},
      emissionYear: '',
      newEmissionData: {},
      updateEmissionData: {},
      fileList: [],
      tableData: [],
      emissionInsertForm: false,
      objectName: '',
      emissionAddForm: false,
      emissionUpdateForm: false,
      limit: 10,
      total: 0,
    }
  },
  mounted:function() {
    this.getAllEmission()
  },
  activated() {
    this.getAllEmission()
  },
  methods: {
    updateEmission(row) {
      //debugger
      console.log("row", row);
      this.updateEmissionData = row;
      //if(this.updateEmissionData.emissionYear==2023) {
      //  this.updateEmissionData.emissionYear = "2023";
      //}
      this.updateEmissionData.emissionYear = this.updateEmissionData.emissionYear.toString()
      console.log(this.updateEmissionData.emissionYear)
      this.emissionUpdateForm = true;
    },
    modifyEmissionData() {
      if (this.updateEmissionData["objectName"] === "" || this.updateEmissionData["objectCategory"] === '' || this.newEmissionData["objectConsumption"] === '' || this.updateEmissionData["emissionType"] === '' || this.updateEmissionData["emissionPurpose"] === '' || this.updateEmissionData["emissionAmount"] === '') {
        this.$message.error("请将表单信息填写完整");
        return;
      }

      if (this.updateEmissionData.emissionType == "直接排放") {
        this.updateEmissionData.emissionType = "0";
      }
      if (this.updateEmissionData.emissionType == "间接排放") {
        this.updateEmissionData.emissionType = "1";
      }
      if (this.updateEmissionData.emissionType == "其他排放") {
        this.updateEmissionData.emissionType = "2";
      }
      console.log("this.updateEmissionData.emissionType", this.updateEmissionData.emissionType)
      axios.post(publicNetworkIpAndPort() + "/api/carbonEmission/updateCarbonEmission", this.updateEmissionData).then((res) => {
        //debugger
        console.log("修改能耗啦")
        console.log("res.data", res.data)
        if (res.data.code == 200) {
          this.$message.success(res.data.data);
        } else {
          this.$message.error(res.data.message);
        }
      }).catch(() => {

      }).finally(() => {
        this.getAllEmission();
        this.emissionUpdateForm = false;
        this.updateEmissionData = {};

      });

    },
    insertEmissionData() {
      if (this.newEmissionData["objectName"] === "" || this.newEmissionData["objectCategory"] === '' || this.newEmissionData["objectConsumption"] === '' || this.newEmissionData["emissionType"] === '' || this.newEmissionData["emissionPurpose"] === '' || this.newEmissionData["emissionAmount"] === '') {
        this.$message.error("请填写完整的能耗信息");
        return;
      } else {
        //this.$refs.upload.submit();
        this.handleEmission();
      }
    },

    handleEmission() {
      console.log("this.newEmissionData", this.newEmissionData)
      axios.post(publicNetworkIpAndPort() + "/api/carbonEmission/addCarbonEmission", this.newEmissionData).then((res) => {
        //debugger
        console.log("res.data", res.data)
        if (res.data.code == 200) {
          this.$message.success(res.data.data);
        } else {
          this.$message.error(res.data.message);
        }
      }).catch(() => {

      }).finally(() => {
        this.getAllEmission();
        this.emissionInsertForm = false;
        this.newEmissionData = {};
      });//会把返回的结果放在.then里。
    },
    insertEmission() {
      this.emissionInsertForm = true;
    },
    deleteEmission(row) {
      console.log(row.id)
      var carbonEmissionId = row.id
      console.log("carbonEmissionId", carbonEmissionId)
      this.$confirm("此操作永久删除当前信息，是否继续？", "提示", { type: "info" }).then(() => {
        axios.get(publicNetworkIpAndPort() + "/api/carbonEmission/deleteCarbonEmissionById?carbonEmissionId=" + carbonEmissionId).then((res) => {
          if (res.data.code === 200) {
            this.$message.success("删除成功")
            // 为了在删除最后一页的最后一条数据时能成功跳转回最后一页的上一页（pageSize=1时不生效）
            let totalPage = Math.ceil((this.total - 1) / this.size)
            let currentPage = this.current > totalPage ? totalPage : this.current
            this.current = currentPage < 1 ? 1 : currentPage
          } else {
            this.$message.error(res.data.message)
          }
        }).catch(() => {
        }).finally(() => {
          this.tableData.length = this.tableData.length - 1;
          if (this.tableData.length === 0) {
            this.cur = this.cur - 1;
            if (this.cur === 0) this.cur = 1;
          }
          this.getAllEmission();
        });
      }).catch(() => {
        this.$message.info("取消操作");
      });
    },
    handleCurrentChange(val) {
      this.current = val
      this.getAllEmission()
    },
    getFileType(file) {
      console.log("filetype")
      console.log("文件类型")
      console.log(file.type)
      if (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        return true;
      } else {
        this.$message({
          message: "上传文件只能是xlsx格式!",
          type: "warning",
        });
        return false;
      }
    },
    handleSuccessEnergy(res) {
      //debugger
      console.log("zhaopian")
      console.log(localStorage.getItem("userId"))
      console.log("zhaopianxinxi")
      console.log("res", res)
      if (res.code === 200) {
        this.$refs.upload.clearFiles();
        this.$message.success(res.data)
        this.emissionAddForm = false;
        this.fileRes = {};
        this.getAllEmission();
      } else {
        this.$refs.upload.clearFiles();
        this.$message.error(res.message);
        this.emissionAddForm = false;
        this.fileRes = {};
      }
    },
    uploadEnergyError() {
      this.$message.error("请选择.xlsx进行上传");
    },
    UploadEnergyUrl: function () {
      console.log("上传能耗啦")
      return publicNetworkIpAndPort() + "/api/carbonEmission/excelCarbonEmission";
    },
    addNewEmission() {
      var files = this.$refs.upload.uploadFiles
      if (files.length == 0) {
        this.$message.error("请选择上传的文件");
        return;
      }
      this.$refs.upload.submit();
    },
    searchCarbon() {
      if (this.objectName !== '')
        searchCarbonByName({ current: this.current, size: this.size, objectName: this.objectName }).then(res => {
          //debugger
          console.log("搜索this.energyName")
          console.log(this.energyName)
          console.log(res)
          console.log("llalalallalal")
          //debugger
          this.tableData = res.data.records
          this.total = res.data.total;
          console.log(res.data.total);
        }).catch(() => {
        }).finally(() => {
        });

    },
    getAllEmission() {
      getAllEmission({ current: this.current, size: this.size }).then(res => {
        //debugger
        console.log("能耗列表res")
        console.log(res)
        this.tableData = res.data.records
        this.total = res.data.total;
        for (var i = 0; i < this.total; i++) {
          if (this.tableData[i] != null && this.tableData[i].emissionType == "0") {
            this.tableData[i].emissionType = "直接排放";
          }
          if (this.tableData[i] != null && this.tableData[i].emissionType == "1") {
            this.tableData[i].emissionType = "间接排放";
          }
          if (this.tableData[i] != null && this.tableData[i].emissionType == "2") {
            this.tableData[i].emissionType = "其他排放";
          }
        }

        this.tableData.emissionType = '直接排放'
        console.log(res.data.total);
      })
    },
    getexcelEmission() {
      //debugger
      this.emissionAddForm = true
    },
  }
}

</script>
<style>
.cell{
  text-align: center;
}
.energyleft,
.energyright {
  display: inline-block;
}

.energyright {
  vertical-align: top !important;
  margin-bottom: 19px;
}

.el-table,
.el-table__expanded-cell {
  background-color: transparent;
}

.el-table th,
.el-table tr {
  background-color: transparent;
}

.el-table__body tr:hover>td {
  background-color: skyblue !important;
}

.el-table th.el-table__cell {
  background-color: skyblue;
  color: #000;
  font-size: 15px;
  height: 50px;
}

.form-item-inline {
  font-size: 13px;
}

.el-table__fixed {
  height: 100% !important;
}

.main-box-admin {
  width: 94%;
  margin: 0 auto;
  text-align: left;
  padding: 3%;
}

.flex-box-header {
  margin-left: 20px;
  margin-right: 15px;
  margin-top: 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
